<?php

namespace MUD;

class DBInterface {
    public $rows=0;
    public $result=array();
    private $prefix;
    private $fd;
    
    public function __construct($host, $username, $password, $database, $prefix){
        if(is_resource($this->fd)){
            return true;
        }else{
            $this->fd = new \mysqli($host, $username, $password, $database);
            
            if($this->fd->connect_errno){
                trigger_error("Failed to connect to database: ".$this->fd->connect_error, $this->fd->connect_errno);
                return false;
            }
            $this->prefix = $prefix;
            return true;
        }
    }
    
    public function select($what, $from, $where, $limit){
        $sql = "SELECT " . $what . "FROM ".$this->prefix.$from;
        if($where){
            $sql .= " WHERE ".$where;
        }
        if($limit){
            $sql .= " LIMIT ".$limit;
        }
        
        return $this->query($sql, true);
    }
    
    public function update($table, $data, $where, $limit=1){
        $sql = "UPDATE ".$table." SET ";
        $add=array();
        foreach($data as $key => $value){
            $add[] = $key."='".$value."'";
        }
        $sql .= implode(",", $add);
        
        if($where){
            $sql.=" WHERE ".$where;
        }
        $sql .= " LIMIT ".$limit;
        
        return $this->query($sql, false);
    }
    
    public function delete($from, $where, $limit=1){
        $sql = "DELETE FROM ".$this->prefix.$from;
        if($where){
            $sql.= " WHERE ".$where;
        }
        $sql .= " LIMIT ".$limit;
        return $this->query($sql, false);
    }
    
    public function insert($table, $data){
        $sql = "INSERT INTO ".$this->prefix.$table;
        $fields=array_keys($data);
        for($i=0,$fc=count($fields);$i<$fc;$i++){
            $fields[$i] = '`'.$fields[$i].'`';
        }
        $sql.="(".implode(',',$fields).") VALUES(";
        
        $values = array();
        for($i=0;$i<$fc;$i++){
            if($data[$i] == 'NOW()'){
                $values[] = $data[$i];
            }else{
                $values[] = "'".$data[$i]."'";
            }
        }
        $sql .= implode(',', $values);
        $sql.=")";
        
        return $this->query($sql, false);
    }
    
    public function query($sql, $result=false){
        $query = $this->fd->query($sql);
        if($this->fd->errno){
            trigger_error($this->fd->error);
            return false;
        }
        
        if($result){
            $this->rows = $query->num_rows;
            $this->result=array();
            if($this->rows > 0){
                while($row = $query->fetch_assoc()){
                    array_push($this->result, $row);
                }
            }
        }
        return true;
    }
    
    public function close(){
        $this->fd->close();
    }
    
    function __destruct(){
        $this->close();
    }
}